/**
 * 
 */
package com.pollyduan.springInitializr;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author: pollyduan
 * @date: 2018年3月21日 下午4:41:46
 *
 */
public class MetadataPullThread extends Thread {
	private OkHttpClient client = new OkHttpClient();

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(1000 * 60 * 5);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			// 延时5分钟执行第一次拉取

			fetch();
			
			try {
				Thread.sleep(1000 * 60 * 60 * 6);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 */
	public void fetch() {
		Request request = new Request.Builder().url(Constants.metadataEndpoint).build();
		String responseBody=null;
		try {
			System.out.println("******fetch from "+Constants.metadataEndpoint+" start...");
			Response response = client.newCall(request).execute();
			responseBody = response.body().string();	
			if(responseBody!=null) {
				Files.write(new File(Constants.metadataLocalFile).toPath(), 
						responseBody.getBytes(),
						StandardOpenOption.CREATE,StandardOpenOption.TRUNCATE_EXISTING);
			}
			System.out.println("******fetch from "+Constants.metadataEndpoint+" success.");
		} catch (IOException e) {
			System.out.println("******fetch from "+Constants.metadataEndpoint+" fail.");
			e.printStackTrace();
		}
	}
}
